package com.taskmanagement.controller;

import com.taskmanagement.entity.Review;
import com.taskmanagement.service.ReviewService;
import com.taskmanagement.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/reviews")
public class ReviewController {

    @Autowired
    private ReviewService reviewService;
    
    @Autowired
    private TaskService taskService;

    @GetMapping("/task/{taskId}")
    public ResponseEntity<?> getReviewByTaskId(@PathVariable BigInteger taskId) {
        try {
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(taskId, userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Review review = reviewService.findByTaskId(taskId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", review);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/task/{taskId}")
    public ResponseEntity<?> createReview(@PathVariable BigInteger taskId, @RequestBody Review review) {
        try {
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(taskId, userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查是否已存在复盘
            Review existingReview = reviewService.findByTaskId(taskId);
            if (existingReview != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "该任务已存在复盘，请使用更新接口");
                return ResponseEntity.badRequest().body(response);
            }
            
            review.setTaskId(taskId);
            Review createdReview = reviewService.createReview(review);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "复盘添加成功");
            response.put("data", createdReview);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateReview(@PathVariable BigInteger id, @RequestBody Review review) {
        try {
            Review existingReview = reviewService.findById(id);
            if (existingReview == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "复盘不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            BigInteger userId = getCurrentUserId();
            // 验证任务是否属于当前用户
            if (taskService.findByIdAndUserId(existingReview.getTaskId(), userId) == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "无权操作此复盘");
                return ResponseEntity.badRequest().body(response);
            }
            
            review.setId(id);
            review.setTaskId(existingReview.getTaskId());
            Review updatedReview = reviewService.updateReview(review);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "复盘更新成功");
            response.put("data", updatedReview);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    private BigInteger getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        return taskService.findByUsername(username).getId();
    }
}
